package com.learn.concurrent.itcast.thread.demo;

import java.util.concurrent.Semaphore;

public class WorkerMachineDemo {

    static class Work implements Runnable {

        private int workNum;//工人工号
        private Semaphore semaphore;//机器数

        public Work(int workNum, Semaphore semaphore) {
            this.workNum = workNum;
            this.semaphore = semaphore;
        }

        @Override
        public void run() {
            try {
                //1.工人要去取机器
                semaphore.acquire();
                //2.打印工人获取到机器，开始工作
                String name = Thread.currentThread().getName();
                System.out.println(name + "获取到机器，开始工作。。。");
                //3.线程睡眠1000描，模拟工人使用机器工作过程
                Thread.sleep(1000);
                //4.使用完毕，释放机器
                System.out.println(name + "使用完毕，释放机器！");
                semaphore.release();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }


    public static void main(String[] args) {

        int wokers = 8;
        Semaphore semaphore = new Semaphore(3);
        for(int i=0;i<wokers;i++){
            new Thread(new Work(i,semaphore)).start();
        }
    }
}
